﻿using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace BookTheBook.Data
{
    public class Database : IDatabase
    {
        private ISessionFactory _factory;

        public ISession Session
        {
            get
            {
                if (_factory == null)
                {
                    _factory = CreateSessionFactory();
                }
                return _factory.OpenSession();
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return
                Fluently.Configure().Database(
                         MsSqlConfiguration.MsSql2008.ConnectionString(ConfigurationManager.
                                              ConnectionStrings["ISDCLibraryConnectionString"].ToString())
                                              .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle")
                                              ).
                         Mappings(m => m.FluentMappings.AddFromAssemblyOf<Database>()).
                         BuildSessionFactory();
        }
    }
}
